import React, { useState, useEffect } from 'react';
import { Card, List, Button, Tag, Space, Alert, Typography, Divider } from 'antd';
import { SyncOutlined, CalendarOutlined } from '@ant-design/icons';
import axios from 'axios';
import type { Task } from '../../types/task';
import { useUserStore } from '../../store/userStore';
import { getTodayRandomTasks } from '../../data/environmentalTasks';

const { Title, Text } = Typography;

// 用于存储已完成任务ID的localStorage键名
const COMPLETED_TASKS_STORAGE_KEY = 'completedEnvironmentalTasks';

const EnvironmentalTasks: React.FC = () => {
  const { user, completeTask, tasks, addTask, resetDailyTasks } = useUserStore();
  const [dailyTasks, setDailyTasks] = useState<Task[]>([]);
  const [lastRefreshDate, setLastRefreshDate] = useState<string>('');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [currentDate, setCurrentDate] = useState(new Date().toISOString().split('T')[0]);
  const [taskRefreshedToday, setTaskRefreshedToday] = useState(false);

  // 初始化及每次打开组件时检查日期
  useEffect(() => {
    console.log("组件挂载，检查是否需要刷新任务");
    const today = new Date().toISOString().split('T')[0];
    const storedDate = localStorage.getItem('lastTaskRefreshDate');
    
    // 更新当前日期
    setCurrentDate(today);
    
    // 检查本地存储中记录的最后刷新日期
    if (storedDate !== today) {
      console.log(`需要刷新任务: 上次刷新(${storedDate || '从未'}) != 今天(${today})`);
      getEnvironmentalTasksFromCurrentTasks();
      setTaskRefreshedToday(true);
    } else {
      console.log(`今天已经刷新过任务: ${storedDate}`);
      setTaskRefreshedToday(true);
      getEnvironmentalTasksFromCurrentTasks();
      setLastRefreshDate(storedDate);
    }
  }, []);
  
  // 当任务列表变化时，更新环保任务显示
  useEffect(() => {
    if (taskRefreshedToday) {
      getEnvironmentalTasksFromCurrentTasks();
    }
  }, [taskRefreshedToday]);
  
  // 从localStorage获取已完成的任务ID列表
  const getCompletedTasksFromStorage = (): string[] => {
    const storedTasks = localStorage.getItem(COMPLETED_TASKS_STORAGE_KEY);
    return storedTasks ? JSON.parse(storedTasks) : [];
  };

  // 从后端获取环保任务
  const getEnvironmentalTasksFromCurrentTasks = async () => {
    try {
      // 调用后端API获取环保任务
      const response = await axios.get('http://localhost:3001/api/tasks/environmental');
      const tasks = response.data.slice(0, 4);
      
      // 从localStorage获取已完成的任务ID列表
      const completedTaskIds = getCompletedTasksFromStorage();
      
      // 标记已完成的任务
      const tasksWithCompletedState = tasks.map((task: { _id: string; [key: string]: any }) => ({
        ...task,
        completed: completedTaskIds.includes(task._id)
      }));
      
      setDailyTasks(tasksWithCompletedState);
      return tasksWithCompletedState;
    } catch (error) {
      console.error('获取环保任务失败:', error);
      return [];
    }
  };

  const handleCompleteTask = async (taskId: string) => {
    try {
      // 从localStorage获取用户ID
      const userId = localStorage.getItem('userId');
      
      // 发送完成任务请求到后端
      await axios.post(`http://localhost:3001/api/tasks/${taskId}/complete`, {
        userId: userId
      });
      
      // 将完成的任务ID存储到localStorage
      const completedTaskIds = getCompletedTasksFromStorage();
      if (!completedTaskIds.includes(taskId)) {
        completedTaskIds.push(taskId);
        localStorage.setItem(COMPLETED_TASKS_STORAGE_KEY, JSON.stringify(completedTaskIds));
      }
      
      // 更新UI上的任务状态
      setDailyTasks(prevTasks => 
        prevTasks.map(task => 
          task._id === taskId ? { ...task, completed: true } : task
        )
      );

      // 重新获取任务列表以确保状态同步
      await getEnvironmentalTasksFromCurrentTasks();
    } catch (error) {
      console.error('完成任务失败:', error);
    }
};

  // 格式化日期显示
  const formatDate = (dateString: string) => {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card 
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={4} style={{ margin: 0 }}>
              <CalendarOutlined style={{ marginRight: 8 }} />
              今日环保任务
            </Title>
            <Space>
              <Text type="secondary">
                当前日期: {formatDate(currentDate)}
              </Text>
              <Button 
                icon={<SyncOutlined spin={isRefreshing} />} 
                // onClick={handleRefreshTasks}
                loading={isRefreshing}
                disabled={lastRefreshDate === currentDate && dailyTasks.length > 0}
                title={lastRefreshDate === currentDate && dailyTasks.length > 0 ? "今天已经刷新过任务，请明天再来！" : "刷新今日任务"}
              >
                {lastRefreshDate === currentDate && dailyTasks.length > 0 ? "今日已刷新" : "重新随机"}
              </Button>
            </Space>
          </div>
        }
      >
        <Alert 
          message="完成这些日常环保任务可以获得绿色能量，提升你的星球健康度!" 
          type="success" 
          showIcon 
          style={{ marginBottom: '16px' }}
        />
        
        <Divider orientation="left">每日随机任务 (4个)</Divider>
        
        {dailyTasks.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <SyncOutlined spin style={{ fontSize: 24, marginBottom: 16 }} />
            <p>正在加载今日任务...</p>
          </div>
        ) : (
          <List
            dataSource={dailyTasks}
            renderItem={task => (
              <List.Item
                actions={[
                  <Button
                    type="primary"
                    onClick={() => handleCompleteTask(task._id)}
                    disabled={task.completed}
                  >
                    {task.completed ? '已完成' : '标记为已完成'}
                  </Button>
                ]}
              >
                <List.Item.Meta
                  title={
                    <Space>
                      {task.title}
                      <Tag color={task.completed ? 'green' : 'blue'}>
                        {task.completed ? '已完成' : '进行中'}
                      </Tag>
                    </Space>
                  }
                  description={task.description}
                />
                <div>
                  <div style={{ color: '#4CAF50', marginBottom: '4px' }}>
                    +{task.reward.greenEnergy} 绿色能量
                  </div>
                  <div style={{ color: '#666' }}>
                    -{task.reward.carbonReduction} kg CO₂
                  </div>
                  {task.reward.waterQuality && (
                    <div style={{ color: '#2196F3' }}>
                      +{(task.reward.waterQuality * 100).toFixed(1)}% 水质改善
                    </div>
                  )}
                </div>
              </List.Item>
            )}
          />
        )}
      </Card>
    </div>
  );
};

export default EnvironmentalTasks;

